//
//  ViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2017/9/1.
//  Copyright © 2017年 YRX. All rights reserved.
//

#import "ViewController.h"
#import "IASubjectItem.h"
#import "IALessonViewController.h"
#import "IATokenManager.h"
#import "MBProgressHUD.h"
#import "JGProgressHUD.h"
#import "IANPLSimilarityService.h"
#import "StudentViewController.h"
#import "QuestionViewController.h"
#import "SettingViewController.h"
#import "IAMetaDataReader.h"
#import "IAHomeSubjectCell.h"

static NSString * const IAHomeCellID = @"IAHomeCellID";
static CGFloat const TitleViewH = 90.0f;

static CGFloat const lrMargin = 14.f;

@interface ViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) NSArray <NSString *> * subjectNames;

@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    IAToken *token = [IATokenManager readToken];
    if (token) {
        NSComparisonResult result = [token.expires_time compare:[NSDate date]];
        if (result != NSOrderedDescending) { // 过期 重新获取token
            [self requestToken];
        }
    } else {
        [self requestToken];
    }
    
    [self setupHeaderView];
    [self setupCollectionView];
}

- (void)setupHeaderView {
    UIView *containerView = [[UIView alloc] init];
    containerView.frame = CGRectMake(0.0f, 64.0f, self.view.cWidth, TitleViewH);
    
    UILabel *aLabel = [[UILabel alloc] init];
    aLabel.frame = CGRectMake(0, 20.0f, containerView.cWidth, containerView.cHeight - 31.0f);
    aLabel.text = @"请选择课程进行答题";
    aLabel.textAlignment = NSTextAlignmentCenter;
    [aLabel setFont:[UIFont systemFontOfSize:19]];
    [containerView addSubview:aLabel];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.frame = CGRectMake(50.0f, CGRectGetMaxY(aLabel.frame), containerView.cWidth - 100.0f, 0.5);
    lineView.backgroundColor = [UIColor lightGrayColor];
    [containerView addSubview:lineView];
    
    [self.view addSubview:containerView];
}

- (void)setupCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    layout.minimumLineSpacing = lrMargin;
    layout.minimumInteritemSpacing = lrMargin;
    layout.sectionInset = UIEdgeInsetsMake(lrMargin, lrMargin, lrMargin, lrMargin);
    
    CGFloat selfWidth = self.view.cWidth;
    // 3列
    CGFloat itemWidth = (selfWidth - lrMargin * 2 - (3 - 1) * lrMargin) / 3;
    
    layout.itemSize = CGSizeMake(itemWidth, itemWidth);
    
    CGRect rect = CGRectMake(0, TitleViewH + 64, self.view.cWidth, self.view.cHeight - TitleViewH - 64 - 44);
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:rect
                                                          collectionViewLayout:layout];
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = YES;
    collectionView.alwaysBounceVertical = YES;
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [collectionView registerNib:[UINib nibWithNibName:@"IAHomeSubjectCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:IAHomeCellID];
    self.collectionView = collectionView;
    [self.view addSubview:collectionView];
}

- (IBAction)showSetting:(id)sender {
    SettingViewController *settingController = [[SettingViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:settingController];
    [self presentViewController:navController animated:YES completion:nil];
}

- (IBAction)showStudents:(UIBarButtonItem *)sender {
    NSArray <IAStudent *> * stus = [IAMetaDataReader getStudents];
    StudentViewController *studentController = [[StudentViewController alloc] initWithStudents:stus];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:studentController];
    [self presentViewController:navController animated:YES completion:nil];
}

- (void)requestToken {
    JGProgressHUD *hud = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleLight];
    hud.textLabel.text = @"初始化数据...";
    [hud showInView:self.view];
    [IATokenManager requestTokenHanler:^(BOOL result, IAToken *token) {
        if (result) {
            hud.textLabel.text = @"数据初始化成功";
        } else {
            hud.textLabel.text = @"数据初始化失败";
        }
        [hud dismissAfterDelay:1.5 animated:YES];
        [self.collectionView reloadData];
    }];
}

-(NSArray<NSString *> *)subjectNames {
    if (!_subjectNames) {
        _subjectNames = [IAMetaDataReader subjectNames];
    }
    return _subjectNames;
}

#pragma mark - collectionView dataSource and delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.subjectNames.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IAHomeSubjectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:IAHomeCellID forIndexPath:indexPath];
    NSString *imageName = [NSString stringWithFormat:@"tpl_ph_one_0%@", @(indexPath.row + 1)];
    NSString *subjectName = self.subjectNames[indexPath.row] ?: @"未来";
    NSString *titleName = [NSString stringWithFormat:@"第%@节\n%@", @(indexPath.row + 1), subjectName];
    cell.imageView.image = [UIImage imageNamed:imageName];
    cell.titleLabel.text = titleName;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *subjectName = self.subjectNames[indexPath.row];
    [IAMetaDataReader getSubjectItemsForName:subjectName completion:^(id obj) {
        QuestionViewController *questionController = [[QuestionViewController alloc]
                                                      initWithSubjectName:subjectName subjects:obj];
        [self.navigationController pushViewController:questionController animated:YES];
    }];
}

@end
